// GeoGebra App Variables
let ggbApp = null;
let currentDirectoryPath = '/';

const parameters = {
    "id": "ggbApplet",
    "showMenuBar": true,
    "showAlgebraInput": true,
    "showToolBar": true,
    "customToolBar": "0 | 1 501 5 19 , 67 | 2 15 45 18 , 7 37 | 514 3 9 , 13 44 , 47 | 16 | 551 550 11 ,  20 22 21 23 , 55 56 57 , 12 | 69 | 510 511 , 512 513 | 533 531 , 534 532 , 522 523 , 537 536 , 535 | 521 520 | 36 , 38 49 560 | 571 30 29 570 31 33 | 17 | 540 40 41 42 , 27 28 35 , 6 , 502",
    "showToolBarHelp": true,
    "showResetIcon": false,
    "enableLabelDrags": false,
    "enableShiftDragZoom": true,
    "enableRightClick": false,
    "errorDialogsActive": false,
    "useBrowserForJS": false,
    "allowStyleBar": false,
    "preventFocus": false,
    "showZoomButtons": true,
    "capturingThreshold": 3,
    "showFullscreenButton": true,
    "scale": 1,
    "disableAutoScale": false,
    "allowUpscale": false,
    "clickToLoad": false,
    "appName": "classic",
    "buttonRounding": 0.7,
    "buttonShadows": false,
    "language": "zh-CN",
    "filename": "./ggb/myfile.ggb",
    "appletOnLoad": function(api) {
        ggbApp = api;
    }
};

// DOM Elements
const fab = document.getElementById('fab');
const fileListPanel = document.getElementById('fileListPanel');
const fileListUl = document.getElementById('fileList');
const fileListTitle = document.getElementById('fileListTitle');
const uploadButton = document.getElementById('uploadButton');

// Initialize GeoGebra Applet
function initGeoGebra() {
    const applet = new GGBApplet(parameters, true);
    applet.setHTML5Codebase('./public/geogebra/HTML5/5.0/web3d/');
    applet.inject('ggbApplet');
}

// Load directory contents
async function loadDirectory(dirPath) {
    const normalizedDirPath = dirPath.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
    currentDirectoryPath = normalizedDirPath;
    fileListTitle.textContent = `文件列表: /${currentDirectoryPath}`;
    fileListUl.innerHTML = '<li class="loading">加载中...</li>';

    try {
        const response = await window.electronAPI.getFileList(normalizedDirPath);
        if (response.success) {
            renderFileList(response.data);
        } else {
            throw new Error(response.error || '获取文件列表失败');
        }
    } catch (error) {
        console.error('Error loading directory:', error);
        fileListUl.innerHTML = `<li>加载目录失败: ${error.message}</li>`;
    }
}

// Render file list
function renderFileList(items) {
    fileListUl.innerHTML = '';

    // Add parent directory link if not root
    if (currentDirectoryPath && currentDirectoryPath !== '/') {
        console.log(currentDirectoryPath);
        const parentPath = currentDirectoryPath.substring(0, currentDirectoryPath.lastIndexOf('/')) || '/';
        const li = document.createElement('li');
        li.classList.add('parent-dir');
        li.innerHTML = `<i class="fas fa-level-up-alt"></i> .. (上级目录)`;
        li.addEventListener('click', () => loadDirectory(parentPath));
        fileListUl.appendChild(li);
    }

    if (!items?.length) {
        if (fileListUl.children.length === 0) {
            fileListUl.innerHTML = '<li>此目录为空</li>';
        }
        return;
    }

    // Render directories
    const directories = items
        .filter(item => item.type === 'directory')
        .sort((a, b) => a.name.localeCompare(b.name));
    
    directories.forEach(dir => {
        const li = document.createElement('li');
        li.innerHTML = `<i class="fas fa-folder"></i> ${dir.name}`;
        li.dataset.path = dir.path;
        li.addEventListener('click', () => {
            currentDirectoryPath = dir.path;
            loadDirectory(dir.path);
        });
        fileListUl.appendChild(li);
    });

    // Render .ggb files
    const ggbFiles = items
        .filter(item => item.type === 'file' && item.name.toLowerCase().endsWith('.ggb'))
        .sort((a, b) => a.name.localeCompare(b.name));
    
    ggbFiles.forEach(file => {
        const li = document.createElement('li');
        li.innerHTML = `<i class="fas fa-file"></i> ${file.name}`;
        li.dataset.filepath = file.path;
        li.addEventListener('click', () => loadFile(file.path).finally(() => {
            fileListPanel.classList.remove('visible');
        }));
        fileListUl.appendChild(li);
    });

    if (!directories.length && !ggbFiles.length && fileListUl.children.length <= 1) {
        const li = document.createElement('li');
        li.textContent = '没有找到符合条件的文件';
        li.style.cursor = 'default';
        li.style.color = '#888';
        fileListUl.appendChild(li);
    }
}

// Load Geogebra file
async function loadFile(filePath) {
    if (!ggbApp) throw new Error("GeoGebra App未初始化");
    
    try {
        parameters.filename = filePath;
        const container = document.getElementById('ggbApplet');
        container.innerHTML = '';
        
        const applet = new GGBApplet(parameters, true);
        applet.setHTML5Codebase('./public/geogebra/HTML5/5.0/web3d/');
        applet.inject('ggbApplet');
    } catch (error) {
        console.error("Error loading file:", error);
        throw error;
    }
}

// Handle file upload
async function handleFileUpload() {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.ggb';
    
    fileInput.onchange = async (e) => {
        const file = e.target.files[0];
        if (!file || !file.name.toLowerCase().endsWith('.ggb')) {
            alert('请选择.ggb文件');
            return;
        }

        uploadButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 上传中...';
        uploadButton.disabled = true;

        try {
            const arrayBuffer = await file.arrayBuffer();
            const response = await window.electronAPI.uploadFile({
                name: file.name,
                path: currentDirectoryPath,
                data: arrayBuffer
            });

            if (!response.success) throw new Error(response.error || '上传失败');
            
            alert(`文件上传成功: ${file.name}`);
            if (fileListPanel.classList.contains('visible')) {
                loadDirectory(currentDirectoryPath);
            }
            loadFile(response.file.path+"/"+file.name);
        } catch (error) {
            console.error('上传错误:', error);
            alert(`上传失败: ${error.message}`);
        } finally {
            uploadButton.innerHTML = '<i class="fas fa-upload"></i> 上传文件';
            uploadButton.disabled = false;
        }
    };
    
    fileInput.click();
}

// Event Listeners
fab.addEventListener('click', () => {
    const isVisible = fileListPanel.classList.toggle('visible');
    if (isVisible) loadDirectory(currentDirectoryPath);
});

document.addEventListener('click', (event) => {
    if (!fab.contains(event.target) && !fileListPanel.contains(event.target) && 
        fileListPanel.classList.contains('visible')) {
        fileListPanel.classList.remove('visible');
    }
});

uploadButton.addEventListener('click', handleFileUpload);

// Initialize app
document.addEventListener('DOMContentLoaded', () => {
    initGeoGebra();
    loadDirectory(currentDirectoryPath);
});
